#include<iostream>
#include<functional>
#include<memory>
#include<sys/wait.h>
#include"Log.hpp"
#include"Socket.hpp"
#include"InetAddr.hpp"
using namespace SocketModule;
using namespace LogModule;
using namespace InetAddrModule;

//主要解决：连接问题，IO通信的问题
//TCPServer不需要关心自己未来传递的信息是什么
//网络版本计算器是长服务
using ioservice_t = std::function<void(std::shared_ptr<Socket>& sock, InetAddr& client)>;
class TcpServer
{
    public:
        TcpServer(uint16_t port, ioservice_t service)
        :_port(port), _listensockptr(std::make_unique<TcpSocket>()), 
        _isrunning(false)
        ,_service(service)
        {
            _listensockptr->BuildTcpSocketMethod(_port);
        }

    void start()
    {
        _isrunning = true;
        while(true)
        {
            InetAddr client;
            auto socket = _listensockptr->Accept(&client); // 1. 和client通信sockfd 2. client 网络地址
            if(socket == nullptr)
              continue;
            LOG(LogLevel::INFO) << "accept success..." << client.StringAddr();
            
            pid_t id = fork();
            if(id < 0)
            {
                LOG(LogLevel::FATAL) << "fork error...";
                exit(FORK_ERR);
            }
            else if(id == 0)
            {
                _listensockptr->Close(); //子进程关闭套接字然后退出，被父进程回收
                if(fork() > 0) 
                {
                    exit(OK);
                }
                //孙子进程(孤儿进程)执行任务，被1号进程回收
                _service(socket, client);
                socket->Close();
                exit(OK);
            }
            else
            {
                //父进程
                socket->Close();
                pid_t rid = ::waitpid(id, nullptr, 0);
                (void)rid;
            }
        }
        _isrunning = false;
    }

    ~ TcpServer(){}

    private:
        uint16_t _port;
        std::unique_ptr<Socket> _listensockptr;
        bool _isrunning;
        ioservice_t _service;
};
